//
//  ForumDetailViewController.m
//  cityCar
//
//  Created by yao on 14-10-31.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "ForumDetailViewController.h"
#import "Connection.h"
#import "ForumDetailCell.h"
#import "WebColor.h"
#import "ForumContentViewController.h"
#import "MJRefresh.h"
#import "DataBaseHandler.h"

@interface ForumDetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, retain)UITableView *myTableView;
@property(nonatomic, retain)NSMutableArray *arrayTopic;

// 收藏的label
@property(nonatomic, retain)UILabel *collectLabel;
// 收藏的button
@property(nonatomic, retain)UIButton *collectButton;

@end

@implementation ForumDetailViewController

- (void)dealloc
{
    [_forum release];
    [_string release];
    [_dic release];
    [_myTableView release];
    [_arrayTopic release];
    [_collectButton release];
    [_collectLabel release];
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        
        self.arrayTopic = [NSMutableArray array];
        self.string = [NSString string];
        self.forum = [[[Forum alloc] init] autorelease];
        self.countx = 1;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupView];
    
    [self startConnection];
    [self setupRefresh];
}

- (void)setupView
{
    
    //    self.title = [self.dic objectForKey:@"Name"];
    
    // 视图控制器的宽和高
    CGFloat x = self.view.frame.size.width;
    CGFloat y = self.view.frame.size.height;
    
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, x, y) style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.rowHeight = 80;
    [self.view addSubview:self.myTableView];
    [_myTableView release];
    
    // 在顶部加一个View
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, x, 64)];
    headView.backgroundColor = [WebColor whiteSmoke];
    [self.view addSubview:headView];
    [headView release];
    
    
    // 在顶部View上加一个label
    UILabel *headLabel = [[UILabel alloc] initWithFrame:CGRectMake((x - 100) / 2, 15, 100, 50)];
    headLabel.text = [self.dic objectForKey:@"Name"];
    headLabel.textAlignment = NSTextAlignmentCenter;
    [headView addSubview:headLabel];
    [headLabel release];
    
    
    // 返回的button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(10, 25, 30, 30);
    [button setImage:[UIImage imageNamed:@"iconfont-fanhui.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    button.tintColor = [WebColor black];
    [headView addSubview:button];
    
    // 收藏
    self.collectButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.collectButton.frame = CGRectMake(x - 40, 25, 30, 30);
    [self.collectButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang-3.png"] forState:UIControlStateNormal];
    [self.collectButton addTarget:self action:@selector(collectButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.collectButton.tintColor = [WebColor black];
    [headView addSubview:self.collectButton];
    
    
    // 显示收藏的label
    self.collectLabel = [[UILabel alloc] initWithFrame:CGRectMake((x - 100) / 2, 200, 100, 30)];
    self.collectLabel.hidden = YES;
    self.collectLabel.textColor = [WebColor white];
    self.collectLabel.alpha = 0.5;
    self.collectLabel.backgroundColor = [WebColor black];
    self.collectLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.collectLabel];
    [_collectLabel release];
    
    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(cartoon) userInfo:nil repeats:YES];
    
}


- (void)startConnection
{
    NSString *str = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v3/bbs/newForums/%@?pageNo=%d&pageSize=19&orderby=replyat", self.string, self.countx];
    
    [Connection networkHandlerWith:str block:^(id result) {
        
        NSMutableArray *array = [result objectForKey:@"topicList"];
        
        // 在topicList数组中遍历字典
        for (NSDictionary *dic in array) {
            self.forum = [[Forum alloc] init];
            
            // kvc赋值
            [self.forum setValuesForKeysWithDictionary:dic];
            self.forum.url = [dic objectForKey:@"uri"];
            self.forum.forumName = [[dic objectForKey:@"author"] objectForKey:@"nickname"];
            self.forum.forumGather.name = self.forum.forumName;
            self.forum.forumGather.Id = [[dic objectForKey:@"author"] objectForKey:@"userId"];
            [self.arrayTopic addObject:self.forum];
        }
        [self settingButton];
        [self.myTableView reloadData];
    }];
    
    
    // 2秒后刷新表格
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //刷新表格
        [self.myTableView reloadData];
        //调用endRefreshing可以结束刷新状态
        [self.myTableView footerEndRefreshing];
        _countx += 1;
    });
    
}

#pragma mark - UITableView协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayTopic.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ForumDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseTopic"];
    if (!cell) {
        cell = [[[ForumDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuseTopic"] autorelease];
    }
    cell.forum = [self.arrayTopic objectAtIndex:indexPath.row];
    cell.selectionStyle = 0;
    return cell;
}

// cell的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ForumContentViewController *contentVC = [[ForumContentViewController alloc] init];
    Forum *forum = [self.arrayTopic objectAtIndex:indexPath.row];
    contentVC.forum = forum;
    [self presentViewController:contentVC animated:YES completion:^{
        
    }];
    
    
}

// tableView设置Cell的格式
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    ForumDetailCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if ([cell respondsToSelector:@selector(tintColor)]) {
        CGFloat cornerRadius = 5.f;
        cell.backgroundColor = [UIColor clearColor];
        CAShapeLayer *layer = [[[CAShapeLayer alloc] init] autorelease];
        CGMutablePathRef pathRef = CGPathCreateMutable();
        CGRect bounds = CGRectInset(cell.bounds, 10, 0);
        bounds.size.width = self.view.bounds.size.width - 20;
        BOOL addLine = NO;
        if (indexPath.row == 0 && indexPath.row == [tableView numberOfRowsInSection:indexPath.section] - 1) {
            CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
        } else if (indexPath.row  == 0) {
            CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
            CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
            addLine = YES;
        } else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
            CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
            CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
        } else {
            CGPathAddRect(pathRef, nil, bounds);
            addLine = YES;
        }
        layer.path = pathRef;
        CFRelease(pathRef);
        layer.fillColor = [UIColor colorWithWhite:1.f alpha:0.8f].CGColor;
        layer.strokeColor = [UIColor lightGrayColor].CGColor;
        if (addLine == YES) {
            
            CALayer *lineLayer = [[[CALayer alloc] init] autorelease];
            CGFloat lineHeight = (1.f / [UIScreen mainScreen].scale);
            lineLayer.frame = CGRectMake(CGRectGetMinX(bounds)+10, bounds.size.height-lineHeight, bounds.size.width-10, lineHeight);
            lineLayer.backgroundColor = tableView.separatorColor.CGColor;
            [layer addSublayer:lineLayer];
        }
        UIView *testView = [[[UIView alloc] initWithFrame:bounds] autorelease];
        [testView.layer insertSublayer:layer atIndex:0];
        testView.backgroundColor = UIColor.clearColor;
        cell.backgroundView = testView;
    }
}


#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 刷新表格
        [self.myTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.myTableView  headerEndRefreshing];
    });
}
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.myTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.myTableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.myTableView addFooterWithTarget:self action:@selector(startConnection)];
    [self.myTableView footerEndRefreshing];
    
}

- (void)buttonClicked:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

// 点击收藏按钮
- (void)collectButtonClicked:(UIButton *)button
{
    DataBaseHandler *handler = [DataBaseHandler shareInstrance];
    
    UIImage *image = [UIImage imageNamed:@"iconfont-shoucang-3.png"];
    UIImage *buttonImage = [button backgroundImageForState:UIControlStateNormal];
    if ([buttonImage isEqual:image]) {
        [button setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang-4.png"] forState:UIControlStateNormal];
        self.collectLabel.hidden = NO;
        self.collectLabel.text = @"收藏成功";
        // 创建表
        [handler createTableModel];
        
        // model类
        ForumGather *forum = [[ForumGather alloc] init];
        forum.name = [self.dic objectForKey:@"Name"];
        forum.Id = self.string;
        
        // 添加表
        [handler insertModel:forum];
        [forum release];
        
    } else {
        [button setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang-3.png"] forState:UIControlStateNormal];
        self.collectLabel.hidden = NO;
        self.collectLabel.text = @"取消收藏";
        [handler deleteModel:self.string];
    }
    
}

// 设置button的背景色
- (void)settingButton
{
    DataBaseHandler *handler = [DataBaseHandler shareInstrance];
    NSString *string = [NSString stringWithFormat:@"%@", self.string];
    for (ForumGather *fav in [handler selectModelAll]) {
        if ([string isEqualToString:fav.Id]) {
            [self.collectButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang-4.png"] forState:UIControlStateNormal];
            break;
        } else {
            [self.collectButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang-3.png"] forState:UIControlStateNormal];
        }
    }
}

// 收藏自动取消
- (void)cartoon
{
    self.collectLabel.hidden = YES;
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
